﻿using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp1
{
    public static class Helpers
    {
        /// <summary>
        /// 获取该日期本周的第一天，也就是星期日
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static DateTime ToWeekFirstDay(this DateTime dt)
        {
            for (int i = 0; i < 7; i++)
            {
                var rsDt = dt.AddDays(-i);
                if (rsDt.DayOfWeek == DayOfWeek.Sunday)
                {
                    return rsDt;
                }
            }
            return dt;
        }
        /// <summary>
        /// 获取本月的第一天
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static DateTime ToMonthFirstDay(this DateTime dt)
        {
            return new DateTime(dt.Year, dt.Month, 1);
        }
        /// <summary>
        /// 上周日期范围
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static Tuple<DateTime, DateTime> ToLastWeek(this DateTime dt)
        {
            var t = dt.AddDays(-7);
            var start = DateTime.Now;
            var end = DateTime.Now;
            for (int i = 0; i < 7; i++)
            {
                var s = t.AddDays(-i);
                if (s.DayOfWeek == DayOfWeek.Sunday)
                {
                    start = s;
                }
                var e = t.AddDays(i);
                if (e.DayOfWeek == DayOfWeek.Saturday)
                {
                    end = e;
                }
            }

            return new Tuple<DateTime, DateTime>(start, end);
        }
        /// <summary>
        /// 是否是本月的最后一天
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static bool IsMonthLastDay(this DateTime dt)
        {
            return dt.AddDays(1).Month != dt.Month;
        }

        /// <summary>
        /// 上月日期范围
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static Tuple<DateTime, DateTime> ToLastMonth(this DateTime dt)
        {
            var t = dt.AddMonths(-1);
            var start = DateTime.Now;
            var end = DateTime.Now;
            for (int i = 0; i < 31; i++)
            {
                var s = t.AddDays(-i);
                if (s.Day == 1)
                {
                    start = s;
                }
                var e = t.AddDays(i);
                if (e.IsMonthLastDay())
                {
                    end = e;
                }
            }
            return new Tuple<DateTime, DateTime>(start, end);
        }
    }
}
